# Makefile for moparse
CXX = g++
CXXFLAGS = -std=c++14 -Wall -Wextra -O2 -Isrc
LDFLAGS = -static-libgcc -static-libstdc++
PROTOC = protoc
LIBS = -lprotobuf -pthread

# 目录定义
SRC_DIR = src
BUILD_DIR = build

# 源文件
SOURCES = $(SRC_DIR)/main.cpp $(SRC_DIR)/moparse.cpp
OBJECTS = $(BUILD_DIR)/main.o $(BUILD_DIR)/moparse.o $(BUILD_DIR)/modb.pb.o
TARGET = moparse

# 头文件依赖
HEADERS = $(SRC_DIR)/moparse.h $(BUILD_DIR)/modb.pb.h

.PHONY: all clean test static static-full static-try

all: $(BUILD_DIR) $(TARGET)

# 尝试静态链接 protobuf（推荐用于 CentOS 7）
static-try: LDFLAGS = -static-libgcc -static-libstdc++
static-try: LIBS = -Wl,-Bstatic -lprotobuf -lz -Wl,-Bdynamic -pthread -lm
static-try: clean $(BUILD_DIR) $(TARGET)

# 静态链接 C++ 标准库（如果系统有静态 protobuf 库）
static: LDFLAGS = -static-libgcc -static-libstdc++
static: LIBS = -Wl,-Bstatic -lprotobuf -Wl,-Bdynamic -pthread
static: clean $(BUILD_DIR) $(TARGET)

# 完全静态编译（需要所有静态库）
static-full: LDFLAGS = -static
static-full: LIBS = -lprotobuf -lz -pthread -lm
static-full: clean $(BUILD_DIR) $(TARGET)

# 创建build目录
$(BUILD_DIR):
	mkdir -p $(BUILD_DIR)

# 生成Protocol Buffers代码
$(BUILD_DIR)/modb.pb.cc $(BUILD_DIR)/modb.pb.h: $(SRC_DIR)/modb.proto | $(BUILD_DIR)
	$(PROTOC) --proto_path=$(SRC_DIR) --cpp_out=$(BUILD_DIR) modb.proto

# 编译目标文件
$(BUILD_DIR)/%.o: $(SRC_DIR)/%.cpp $(HEADERS) $(BUILD_DIR)/modb.pb.h | $(BUILD_DIR)
	$(CXX) $(CXXFLAGS) -I$(BUILD_DIR) -c $< -o $@

$(BUILD_DIR)/modb.pb.o: $(BUILD_DIR)/modb.pb.cc $(BUILD_DIR)/modb.pb.h
	$(CXX) $(CXXFLAGS) -c $(BUILD_DIR)/modb.pb.cc -o $(BUILD_DIR)/modb.pb.o

# 链接可执行文件（默认：静态链接 C++ 标准库，动态链接 protobuf）
$(TARGET): $(OBJECTS)
	$(CXX) $(LDFLAGS) $(OBJECTS) -o $(TARGET) $(LIBS)

# 运行测试
test: $(TARGET)
	cd tests && make test

# 清理
clean:
	rm -rf $(BUILD_DIR) $(TARGET)
	cd tests && make clean

# 安装
install: $(TARGET)
	cp $(TARGET) /usr/local/bin/

# 卸载
uninstall:
	rm -f /usr/local/bin/$(TARGET)